package framework.model;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class SelectiveIterator<T> implements Iterator<T> {
    //List<T> data;
    IPredicate<T> p;
    T now, next;
    Iterator<T> it;
    public SelectiveIterator(Iterator<T> c, IPredicate<T> pred) {
        it = c;
        p = pred;
        init();
    }
    private void init() {
        now = next = null;
        while(it.hasNext()) {
            T e = it.next();
            if (p.check(e)) {
                next = e;
                break;
            }
        }       
    }
    
    @Override
    public boolean hasNext() {
        if(next == null )
            return false;
        else {
            return true;
        }
    }

    @Override
    public T next() {
       if(next == null)
           throw new NoSuchElementException("No more element");
       now = next;
       // Find the next element
       boolean flag = false;
       while(it.hasNext()) {
           T tmp = it.next();
           if(p.check(tmp)) {
               next = tmp;
               flag = true;
               break;
           }
       }
       if(!flag) {
           next = null;
       }
       // End find
       return now;
    }

    @Override
    public void remove() {
        it.remove();
    }    
}
